<script lang='ts'  setup>
import { computed, onMounted, reactive, ref } from 'vue'
import api from '@/api'
import { ElMessage, ElMessageBox, FormRules } from 'element-plus';

// 查询条件
const query = ref<{ deptName: string }>({ deptName: '' })
const handleQuery = async () => {
    const { data: res } = await api.deptApi(query.value, 'get')
    depts.value = res
}
handleQuery()

/**
* @author LoneWolf
* table area
*/

const depts = ref()
const editMode = ref(false)
const columns = ref([
    { label: '部门名称', prop: 'deptName' },
    { label: '负责人', prop: 'userName' },
    { label: '更新时间', prop: 'updateTime' },
    { label: '创建时间', prop: 'createTime' },
])
const handleEdit = (row: any) => {
    setTimeout(() => {
        deptForm.value.deptName = row.deptName
        deptForm.value.leaderId = parseInt(row.userId)
        deptForm.value.parentId = row.parentId.slice().pop()
        deptForm.value._id = row._id
    })
    editMode.value = dialogVisible.value = true
}
const handleDel = ({ _id, deptName }: { _id: string, deptName: string }) => {
    ElMessageBox.confirm(`确认删除部门${deptName}吗？`, '提示', { cancelButtonText: '取消', confirmButtonText: '确定' }).then(async () => {
        try {
            await api.deptApi({ _id }, 'delete')
            ElMessage.success(`${deptName}删除成功`)
            handleQuery()
        } catch (error) {
            ElMessage.error(`删除失败：${error}`)
        }
    }).catch(() => { })
}

/**
* @author LoneWolf
* dialog
*/
const deptForm = ref<{
    parentId?: string
    deptName?: string
    leaderId?: number
    _id?: string
}>({})
const deptFormRef = ref()
const dialogVisible = ref(false)
const users = ref()
const deptFormRules = reactive<FormRules>({
    deptName: [
        { required: true, message: '请输入部门名称', trigger: 'blur' }
    ],
    leaderId: [
        { required: true, message: '请选择负责人', trigger: 'blur' }
    ]
})
const leader = computed(() => {
    return users.value.find((item: { userId: number, userEmail: string }) => {
        return item.userId === deptForm.value.leaderId
    })
})
onMounted(async () => {
    users.value = await (await api.getUserListApi({ pageNum: 1, pageSize: 999 })).data.list
})
const handleClose = () => {
    ElMessageBox.confirm(
        `确定退出${editMode.value ? '编辑' : '创建'}部门吗？`,
        `${editMode.value ? '编辑' : '创建'}部门`,
        {
            showClose: false,
            cancelButtonText: '取消',
            confirmButtonText: '确定',
        }
    )
        .then(() => {
            dialogVisible.value = false
            deptFormRef.value.resetFields()
        })
        .catch(() => { })
}


const handleCommit = () => {
    deptFormRef.value.validate(async (isValid: boolean) => {
        if (isValid) {
            try {
                await api.deptApi(deptForm.value, editMode.value ? 'put' : 'post')
                deptFormRef.value.resetFields()
                dialogVisible.value = false
                handleQuery()
                ElMessage.success('操作成功')
            } catch (error) {
                ElMessage.error('操作失败')
            }



        }
    })
}



</script>

<template>
    <div id='DeptManage'>
        <div class=" p-[20px] pb-0   card overflow-hidden ">
            <!-- 条件查询表单区域 -->
            <el-form inline :model="query">
                <el-form-item label="部门名称" prop="deptName">
                    <el-input placeholder="请输入部门名称" v-model.trim="query.deptName" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery">查询</el-button>
                    <el-button type="danger" @click="query.deptName = ''">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class=" h-[20px] bg-slate-50" />
        <div class=" card ">
            <!-- 操作区域 -->
            <div class=" p-[20px]">
                <el-button type="primary" @click="editMode = false; dialogVisible = true; ">创建</el-button>
            </div>
            <el-table :data="depts" row-key="_id" default-expand-all>
                <el-table-column v-for="column in columns" :label="column.label" :prop="column.prop" />
                <el-table-column label="操作" width="150px" fixed="right">
                    <template #default="scope">
                        <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button type="danger" @click="handleDel(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

        </div>

        <el-dialog v-model="dialogVisible" :title="`${editMode ? '编辑' : '创建'}部门`" width="30%"
            :before-close="handleClose" :show-close="false">
            <el-form :model="deptForm" label-width="auto" ref="deptFormRef" :rules="deptFormRules">
                <el-form-item label="上级部门" prop="parentId">
                    <!-- <el-tree-select v-model="deptForm.parentId" :data="depts" check-strictly placeholder="请选择上级部门"
                        default-expand-all :props="{ label: 'deptName', value: '_id' }" /> -->
                    <el-cascader :options="depts" v-model="deptForm.parentId"
                        :props="{ label: 'deptName', value: '_id', checkStrictly: true }" placeholder="请选择上级部门" />
                </el-form-item>
                <el-form-item label="部门名称" prop="deptName">
                    <el-input placeholder="请输入部门名称" v-model.trim="deptForm.deptName" />
                </el-form-item>
                <el-form-item label="负责人" prop="leaderId">
                    <el-select v-model="deptForm.leaderId" placeholder="请选择负责人">
                        <el-option v-for="user in users" :label="user.userName" :value="user.userId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="负责人邮箱">
                    <el-input :value="leader?.userEmail" disabled />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button size="default" @click="handleClose">取消</el-button>
                <el-button type="primary" size="default" @click="handleCommit">提交</el-button>
            </template>
        </el-dialog>
    </div>
</template>
